package com.weiai.wedding.web.cases;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.weiai.wedding.entity.cases.Cases;
import com.weiai.wedding.entity.cases.CasesContent;
import com.weiai.wedding.entity.cases.Resources;
import com.weiai.wedding.service.ServiceException;
import com.weiai.wedding.service.cases.CasesService;
import com.weiai.wedding.util.ConUtils;
import com.weiai.wedding.util.DataTablesParamUtility;
import com.weiai.wedding.util.DataTablesReturnObject;
import com.weiai.wedding.util.Pagination;


import sun.misc.BASE64Decoder;

/**
 * 案例
 * @author wangweiheng
 *
 */
@Controller
@RequestMapping(value="/cases/cases")
public class CasesController {
	@Autowired
	private CasesService casesService;
	
	@RequestMapping(value="")
	public String list(Model model){
		return "cases/cases/casesList";
	}
	
	@RequestMapping(value="list")
	@ResponseBody
	public DataTablesReturnObject<Cases> query(Model model,Cases cases,HttpServletRequest req){
		Pagination<Cases> page = DataTablesParamUtility.buildExpPage(req);
		String sEcho = req.getParameter("sEcho");
		page = casesService.findList(cases, page);
		DataTablesReturnObject<Cases> dataTablesReturnObject = DataTablesParamUtility.toExpDataTablesReturnObject(sEcho, page);
		return dataTablesReturnObject;
	}
	/**
	 * 从任务中查询审核通过的案例
	 * @param model
	 * @param cases
	 * @param req
	 * @return
	 */
	@RequestMapping(value="tasklist")
	@ResponseBody
	public DataTablesReturnObject<Cases> querycases(Model model,Cases cases,HttpServletRequest req){
		Pagination<Cases> page = DataTablesParamUtility.buildExpPage(req);
		String sEcho = req.getParameter("sEcho");
		page = casesService.findCasesList(cases, page);
		DataTablesReturnObject<Cases> dataTablesReturnObject = DataTablesParamUtility.toExpDataTablesReturnObject(sEcho, page);
		return dataTablesReturnObject;
	}
	
	@RequestMapping(value = "create")
	public String createForm(Model model){
		model.addAttribute("cases",new Cases());
		model.addAttribute("actionId", "1");
		return "cases/cases/casesForm";
	}
	
	@RequestMapping(value = "save")
	@ResponseBody
	public String saveForm(Cases cases,BindingResult errorResult,@RequestParam MultipartFile file,RedirectAttributes redirectAttributes){
		if(file==null || file.getSize()==0){
			throw new ServiceException("文件内容为空！请重新上传");
		}
		String fileName = ConUtils.formatDate(new Date(),"yyMMddHHmmss")+file.getOriginalFilename();
		try {
			InputStream is = file.getInputStream();
			//resourcesService.saveResources(po, fileName, is);
			casesService.save(cases,fileName,is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		redirectAttributes.addFlashAttribute("message","添加案例成功");
		return "true";
	}
	
	@RequestMapping(value="view/{id}")
	public String viewForm(@PathVariable("id")   
		    Long id,Model model){
		Cases cases = casesService.findCasesById(id);
		model.addAttribute("cases", cases);
		return "cases/cases/casesView";
	}
	
	@RequestMapping(value="audit/{id}")
	public String auditForm(@PathVariable("id")   
		    Long id,Model model){
		Cases cases = casesService.findCasesById(id);
		model.addAttribute("cases", cases);
		model.addAttribute("audit","1");
		return "cases/cases/casesView";
	}
	
	@RequestMapping(value="auditCases")
	public String audit(HttpServletRequest req,RedirectAttributes redirectAttributes){
		String id = req.getParameter("casesId");
		String auditDesc= req.getParameter("auditDesc");
		String auditType = req.getParameter("auditType");
		casesService.audit(new Long(id), auditDesc, auditType);
		redirectAttributes.addFlashAttribute("message","审核案例成功");
		return "redirect:/cases/cases";
	}
	
	@RequestMapping(value="update/{id}")
	public String updateForm(@PathVariable("id")   
		    Long id,Model model,RedirectAttributes redirectAttributes) throws IOException{
		if(!casesService.checkDelete(id)){
			Cases cases = casesService.findCasesById(id);
			List list = cases.getCasesInfoList();
			if(list!=null && list.size()>0){
				model.addAttribute("listsize", list.size());
			}
			model.addAttribute("actionId", "2");
			model.addAttribute("cases", cases);
			return "cases/cases/casesForm";
		}else{
			redirectAttributes.addFlashAttribute("message","案例正在使用中，不能修改");
			return "redirect:/cases/cases";
		}
	}
	
	@RequestMapping(value="update")
	@ResponseBody
	public String update(Cases cases,@RequestParam MultipartFile file,BindingResult errorResult,RedirectAttributes redirectAttributes){
		if(file==null || file.getSize()==0){
			throw new ServiceException("文件内容为空！请重新上传");
		}
		String fileName = ConUtils.formatDate(new Date(),"yyMMddHHmmss")+file.getOriginalFilename();
		try {
			InputStream is = file.getInputStream();
			//resourcesService.saveResources(po, fileName, is);
			casesService.update(cases,fileName,is);
			//casesService.save(cases,fileName,is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		redirectAttributes.addFlashAttribute("message","修改案例成功");
		return "false";
	}
	
	
	
//	@RequestMapping(value="viewImg/{id}")
//	public void viewImg(@PathVariable("id")Long id,HttpServletResponse response){
//		CasesContent content = casesService.findCasesContentById(id);
//		response.setContentType("image/jpeg");   
//	    response.setCharacterEncoding("UTF-8");   
//	    OutputStream outputSream;
//		BASE64Decoder base = new BASE64Decoder();
//		if(content!=null){
//			try {
//				//outputSream = response.getOutputStream();
//				//byte[] decodeBuffer = base.decodeBuffer(new String(content.getResContent(), "UTF-8"));
//				outputSream.write(decodeBuffer);
//				outputSream.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//	}
	
	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id")Long id,
			RedirectAttributes redirectAttributes){
		//检查案例是否在执行
		if(!casesService.checkDelete(id)){
			
			casesService.deleteCases(id);
			redirectAttributes.addFlashAttribute("message","删除案例成功");
		}else{
			redirectAttributes.addFlashAttribute("message","案例正在使用中，不能删除");
		}
		return "redirect:/cases/cases";
	}
	
	@ResponseBody
	public String checkFilesize(Cases cases,BindingResult errorResult){
		if(casesService.checkFilesize(cases)){
			return "true";
		}
		return "false";
	}
	
	@RequestMapping(value = "viewPhoto/{id}")
	public void getPhotoById (@PathVariable("id")Long id,HttpServletResponse response){   
	    Cases cases = casesService.findCasesById(id);
	    String path = cases.getResourcesDir();
	    response.setContentType("image/jpeg");   
	    response.setCharacterEncoding("UTF-8");   
	    OutputStream outputSream;
	    FileInputStream is;
		try {
			outputSream = response.getOutputStream();
			is = new FileInputStream (path);
			int len = 0;   
		    byte[] buf = new byte[1024];   
		    while ((len = is.read(buf, 0, 1024)) != -1) {   
		        outputSream.write(buf, 0, len);   
		    }   
		    outputSream.close();
		    is.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}  
}
